var tree, zNodes;
var rowid_, authorization_;
var setting = {
	check : {
		enable : true,
		chkStyle : "checkbox"/*,
				chkboxType: { "Y" : "ps", "N" : "ps"  }*/
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "pid"
		},
		view : {
			dblClickExpand : false,// 双击节点图标展开节点
			selectedMulti : false
		}
	},
	callback : {
		onCheck : zTreeOnCheck
	}
};

// ztree 勾选事件
function zTreeOnCheck(event, treeId, treeNode) {
	if (treeNode.checked) {// 判断勾选
		if (authorization_ == "behaviorAuthorization") {
			var data_ = {
				"roleresource.roleid" : rowid_,
				"roleresource.resourceid" : treeNode.id
			};
			authorization("/rbac/addRoleResources", data_);
		}
		if (authorization_ == "menuAuthorization") {
			var data_ = {
				"roleresource.roleid" : rowid_,
				"roleresource.resourceid" : treeNode.id
			};
			authorization("/rbac/addRoleResources", data_);
		}
		if (authorization_ == "apTypeAuthorization"){
			var data_ = {
					"sprole.roleid" : rowid_,
					"sprole.spid" : treeNode.id
				};
				authorization("/rbac/addSprole", data_);
		}
		if (authorization_ == "articleCategoryAuthorization") {
			var data_ = {
					"acttyperole.roleid" : rowid_,
					"acttyperole.articletypeid" : treeNode.id
				};
			authorization("/rbac/addArticleTypeRole", data_);
		}
	} else {
		if (authorization_ == "behaviorAuthorization") {
			var data_ = {
				"roleresource.resourceid" : treeNode.id,
				"roleresource.roleid" : rowid_
			};
			authorization("/rbac/deleteRoleResources", data_);
		}
		if (authorization_ == "menuAuthorization") {
			var data_ = {
				"roleresource.resourceid" : treeNode.id,
				"roleresource.roleid" : rowid_
			};
			authorization("/rbac/deleteRoleResources", data_);
		}
		if (authorization_ == "apTypeAuthorization"){
			var data_ = {
					"sprole.roleid" : rowid_,
					"sprole.spid" : treeNode.id
				};
				authorization("/rbac/deleteSprole", data_);
		}
		if (authorization_ == "articleCategoryAuthorization") {
			var data_ = {
					"acttyperole.roleid" : rowid_,
					"acttyperole.articletypeid" : treeNode.id
				};
			
			authorization("/rbac/deleteArticleTypeRole", data_);
			
		}
		
	}
};

function authorization(url, data) {
	$.ajax({
		type : "post",
		async : false,
		data : data,
		url : url,
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				var type_ = '';
				if (authorization_ == "menuAuthorization") {
					type_ = "menu";
					var data_ = {
							"roleid" : rowid_,
							"type" : type_
						};
					getZtreeData("/rbac/getResourceByRoleid", data_);
				}
				if (authorization_ == "behaviorAuthorization") {
					type_ = "action";
					var data_ = {
							"roleid" : rowid_,
							"type" : type_
						};
					getZtreeData("/rbac/getResourceByRoleid", data_);
				}
				if (authorization_ == "apTypeAuthorization") {
					var data_ = {
							"roleid" : rowid_
						};
					getZtreeData("/rbac/getSproleByroleid", data_);
				}
				if(authorization_ == "articleCategoryAuthorization"){
					var data_ = {
						"roleid" : rowid_
					};
					getZtreeData("/rbac/getActTypeTreeByroleid", data_);
				}
			}
		}
	});
}

$(document).ready(function() {
	getRoleDatagrid();
	$('#rolename,#nickname').validatebox({
		required : true
	});
	

});

function getRoleDatagrid() {
	$('#roleDatagrid')
			.datagrid(
					{
						title : '岗位管理',
						url : '/rbac/getAllRole',
						width : (getWindowSize()[0] - 30),
						height : (getWindowSize()[1] - 50),
						loadMsg : '装载中...',
						nowrap : true, // 如果为true，则在同一行中显示数据。设置为true可以提高加载性能。
						striped : true, // 显示斑马线效果
						// collapsible : true, //显示可折叠按钮
						checkbox : true, // 显示复选框
						fitColumns : true, // 适应网格的宽度，防止水平滚动
						singleSelect : false, // 只允许选择一行
						rownumbers : true, // 显示一个行号列
						remoteSort : false, // 从服务器对数据进行排序
						pagination : true, // 显示分页工具栏
						checkOnSelect : true, // 当用户点击行的时候该复选框就会被选中或取消选中
						pageSize:20,
						pageList : [ 10,20,50, 100, 200 ], // 页面大小选择列表
						columns : [ [
								{
									field : 'id',
									title : 'ID',
									width : 100,
									align : 'center',
									checkbox : true
								},
								{
									field : 'rolename',
									title : '岗位名称',
									width : 100,
									align : 'center',
									sortable : true
								},
								{
									field : 'nickname',
									title : '别称',
									width : 100,
									align : 'center',
									sortable : true
								},
								{
									field : 'opt',
									title : '操作',
									width : 400,
									align : 'center',
									sortable : true,
									formatter : function(value, row, index) {
										return '<a href="javascript:void(0);" id="DataAdd" onclick="behaviorAuthorization(\''
												+ row.id
												+ '\');">行为授权</a>&nbsp;'
												+ '<a href="javascript:void(0);" id="DataAdd" onclick="menuAuthorization(\''
												+ row.id
												+ '\');">菜单授权</a>&nbsp;';
												/*+ '<a href="javascript:void(0);" id="DataAdd" onclick="articleCategoryAuthorization(\''
												+ row.id
												+ '\');">文章类目授权</a>&nbsp;'
												+ '<a href="javascript:void(0);" id="DataAdd" onclick="apTypeAuthorization(\''
												+ row.id
												+ '\');">产品服务授权</a>';*/
									}
								} ] ],
						toolbar : '#roleDatagridMenus',
						onDblClickCell : function() {
							// var row = $('#gzrllb').datagrid('getSelected');
						}
					});
}

function getZtreeData(url, data) {
	var result;
	$.ajax({
		type : "post",
		async : false,
		data : data,
		url : url,
		dataType : "json",
		success : function(result) {

			//zNodes = result[0];
			//zNodes = result;
			//tree = $.fn.zTree.init($("#tree"), setting, zNodes);
			tree = $.fn.zTree.init($("#tree"), setting, result);

			zNodes = result;

		}
	});
	//tree = $.fn.zTree.init($("#tree"), setting, result);
}

function behaviorAuthorization(rowid) {
	$('#treeDialog').dialog({
		title : "行为授权",
		width : 300,
		height : 500,
		left : (getWindowSize()[0] - 300) * 0.5,
		top : (getWindowSize()[1] - 500) * 0.5,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '确定',
			handler : function() {
				$('#treeDialog').window('close');
			}
		} ]
	});
	rowid_ = rowid;
	authorization_ = "behaviorAuthorization";
	var data_ = {
		"roleid" : rowid,
		"type" : "action"
	};
	getZtreeData("/rbac/getResourceByRoleid", data_);
}

function menuAuthorization(rowid) {
	$('#treeDialog').dialog({
		title : "菜单授权",
		width : 300,
		height : 500,
		left : (getWindowSize()[0] - 300) * 0.5,
		top : (getWindowSize()[1] - 500) * 0.5,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '确定',
			handler : function() {
				$('#treeDialog').window('close');
			}
		} ]
	});
	rowid_ = rowid;
	authorization_ = "menuAuthorization";
	var data_ = {
		"roleid" : rowid,
		"type" : "menu"
	};
	getZtreeData("/rbac/getResourceByRoleid", data_);
}

function articleCategoryAuthorization(rowid) {
	$('#treeDialog').dialog({
		title : "文章类目授权",
		width : 300,
		height : 500,
		left : (getWindowSize()[0] - 300) * 0.5,
		top : (getWindowSize()[1] - 500) * 0.5,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '确定',
			handler : function() {
				$('#treeDialog').window('close');
			}
		} ]
	});
	rowid_ = rowid;
	authorization_ = "articleCategoryAuthorization";
	var data_ = {
		"roleid" : rowid
	};
	getZtreeData("/rbac/getActTypeTreeByroleid", data_);
}

function apTypeAuthorization(rowid) {
	$('#treeDialog').dialog({
		title : "产品服务授权",
		width : 300,
		height : 500,
		left : (getWindowSize()[0] - 300) * 0.5,
		top : (getWindowSize()[1] - 500) * 0.5,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '确定',
			handler : function() {
				$('#treeDialog').window('close');
			}
		} ]
	});
	rowid_ = rowid;
	authorization_ = "apTypeAuthorization";
	var data_ = {
		"roleid" : rowid
	};
	getZtreeData("/rbac/getSproleByroleid", data_);
}

function addDialog() {
	openDialog("添加");
}
//填出修改角色对话框
function editDialog() {
	var rows = $("#roleDatagrid").datagrid("getSelections");
	if (rows == null || rows == "" || rows.length > 1) {
		$.messager.alert('警告', '请选中一行!', 'warning');
		return;
	}
	openDialog("修改");
	$.ajax({
		type : "POST",
		url : "/rbac/getSingleRole",
		data : {
			"role.id" : rows[0].id
		},
		dataType : "json",
		success : function(result) {
			$("#roleid").val(result.msg.id);
			$("#nickname").val(result.msg.nickname);
			$("#rolename").val(result.msg.rolename);
			$("#folderForm").form('validate');
		}
	});
}
//添加角色
function addrole() {
	$.ajax({
		type : "POST",
		url : "/rbac/addRole",
		data : {
			'role.nickname' : $("#nickname").val(),
			'role.rolename' : $("#rolename").val()
		},
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				$('#roleDatagrid').datagrid('reload');
				$('#dialog').window('close');
			}
		}
	});
}
//修改角色
function editrole() {
	$.ajax({
		type : "POST",
		url : "/rbac/updateRole",
		data : {
			'role.id' : $("#roleid").val(),
			'role.nickname' : $("#nickname").val(),
			'role.rolename' : $("#rolename").val()
		},
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				$('#roleDatagrid').datagrid('reload');
				$('#dialog').window('close');
			}
		}
	});
}
//删除角色
function delrole() {
	//获得选中行
	var rows = $("#roleDatagrid").datagrid("getSelections");
	if (rows == null || rows == "") {
		$.messager.alert('警告', '请选中一行!', 'warning');
		return;
	}
	var list_ = {};
	for (var i = 0; i < rows.length; i++) {
		list_["roles[" + i + "].id"] = rows[i].id;
	}
	$.messager.confirm('确认', '您确认想要删除记录吗？', function(r) {
		if (r) {
			$.ajax({
				type : "POST",
				url : "/rbac/deleteRole",
				data : {
					'role.id':rows[0].id
				},
				dataType : "json",
				// traditional: true,
				success : function(result) {
					if (result.msg == "ok") {
						$('#roleDatagrid').datagrid('reload');
						$('#dialog').window('close');
					}
				}
			});
		}
	});
}
function clearCache() {
	$("#roleid").val("");
	$("#nickname").val("");
	$("#rolename").val("");
}
// 打开窗口
function openDialog(title) {
	clearCache();
	$('#dialog').dialog({
		title : title,
		width : 300,
		height : 340,
		left : (getWindowSize()[0] - 250) * 0.5,
		top : (getWindowSize()[1] - 140) * 0.5,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '保存',
			handler : function() {
				if ($("#folderForm").form('validate')) {
					if ($('#roleid').val() == "") {
						addrole();
					} else {
						editrole();
					}
				} else {
					$.messager.alert('错误', '有信息未按要求填写!', 'warning');
				}
			}
		}, {
			text : '关闭',
			handler : function() {
				$('#dialog').window('close');
			}
		} ]
	});
	$("#folderForm").form('validate');
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement
			&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body
			&& (document.body.clientWidth || document.body.clientHeight)) {
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return ([ myWidth, myHeight ]);
}